import axios from "axios";
import config from "./config";
import Cookies from "js-cookie";
import router from "../router";
import qs from 'qs'

export class BaseApi {
  servers;

  constructor(props) {
    this.servers = axios.create({
      baseURL: props,
      headers: config.headers,
      timeout: config.timeout,
      withCredentials: config.withCredentials
    })

    // request拦截器
    this.servers.interceptors.request.use(
      config => {
        let token = Cookies.get('token')
        // 1. 请求开始的时候可以结合 vuex 开启全屏 loading 动画
        // console.log(store.state.loading)
        // console.log('准备发送请求...')
        // 2. 带上token
        if(token) {
          config.headers.token = token
        } else {
          // 重定向登录页面
          router.push('/login')
        }
        // 根据请求方法，序列化传来的参数，根据后端需求是否序列化
        if (config.method === 'post') {
          // if (config.data.__proto__ === FormData.prototype
          // || config.url.endsWith('path')
          // || config.url.endsWith('mark')
          // || config.url.endsWith('patchs')) {
          //
          // } else {
          //   config.data = qs.stringify(config.data)
          // }
        }
        return config
      },
      error => {
        console.log('request:', error)
        // 1. 判断请求超时
        if(error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
          console.log('timeout请求超时')
          // return service.request(originalRequest) // 再重复请求一次
        }
        // 2. 需要重定向到错误页面
        const errorInfo = error.response
        console.log(errorInfo)
        if (errorInfo) {
          error = errorInfo.data // 页面那边catch的时候就能拿到详细的错误信息，看最下边的Promise.reject
          const errorStatus = errorInfo.status
          router.push({path: '/error/${errorStatus}'})
        }
        // 在调用的那边可以拿到（catch)你想返回的错误信息
        return Promise.reject(error)
      }
    )
    // response拦截器
    this.servers.interceptors.response.use(
      response => {
        let data
        if(response.data === undefined) {
          data = JSON.parse(response.request.responseText)
        } else {
          data = response.data
        }
        switch (data.rc) {
          case 1:
            console.log(data.desc)
            break;
          case 0:
            // store.commit('changeState')
            console.log('登录成功')
          default:
        }
        // 若不是正确的返回code，且已经登录，就抛出错误
        // const err = new Error(data.desc)
        // err.data = data
        // err.response = response
        // throw err

        return data
      },
      err => {
        if (err && err.response) {
          switch (err.response.status) {
            case 400:
              err.message = '请求错误'
              break
            case 401:
              err.message = '未授权，请登录'
              break
            case 403:
              err.message = '拒绝访问'
              break
            case 404:
              err.message = `请求地址出错: ${err.response.config.url}`
              break
            case 408:
              err.message = '请求超时'
              break
            case 500:
              err.message = '服务器内部错误'
              break
            case 501:
              err.message = '服务未实现'
              break
            case 502:
              err.message = '网关错误'
              break
            case 503:
              err.message = '服务不可用'
              break
            case 504:
              err.message = '网关超时'
              break
            case 505:
              err.message = 'HTTP版本不受支持'
              break
            default:
          }
        }
        console.error(err)
        return Promise.reject(err) // 返回接口返回的错误信息
      }
    )
  }

  connection (method = 'GET', url, body, fileList, fileKey = 'files') {
    // this.getStatusToken()
    // if (typeof body !== 'object') body = {}
    method = method.toLocaleLowerCase()
    if (fileList && (fileList instanceof Array)) {
      let headers = {'Content-Type': 'multipart/form-data'}
      const param = new window.FormData()
      for (const key in body) {
        if ({}.hasOwnProperty.call(body, key)) param.append(key, body[key])
      }
      fileList.forEach(file => param.append(fileKey, file))
      return Promise.resolve(this.servers[method](url, param, {headers}))
    }
    if (method === 'get') {
      console.log(body)
      console.log(qs.stringify(body))
      url = url + (url.indexOf('?') > 0 ? '&' : '?' + qs.stringify(body))
      body = {}
    }
    // if (method === 'post')
      // NProgress.start()
    return Promise.resolve(this.servers[method](url, body))
  }
}
export const generatorServer = new BaseApi(process.env.BASE_GENERATOR_URL);// 基础代码生成平台管理
export const systemServer = new BaseApi(process.env.BASE_SYSTEM_URL);
